package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.TimeForDataUtil;
import com.sky.utils.WeChatLoginUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatLoginUtil weChatLoginUtil;

    @Autowired
    private UserMapper userMapper;


    public User login(UserLoginDTO userLoginDTO) {
        if (userLoginDTO.getCode() == null || userLoginDTO.getCode().trim().equals("")) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        String openid = weChatLoginUtil.getLogin(userLoginDTO.getCode());
        log.info("openid的值为: {}", openid);
        User user = userMapper.getUserByOpenId(openid);

        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }

        return user;
    }

    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();

        // 获取时间范围内的所有用户
        TimeForDataUtil timeForDataUtil = new TimeForDataUtil();
        List<LocalDateTime> localDateTimes = timeForDataUtil.timeForData_YYMMDDHHMMSS(begin, end);
        LocalDateTime beginTime = localDateTimes.get(0);
        LocalDateTime endTime = localDateTimes.get(1);

        List<User> allUsers = userMapper.getAllUsers(beginTime, endTime);

        // 用于存储每日的新增用户数和总用户量
        Map<LocalDate, Integer> dailyNewUsers = new HashMap<>();
        Map<LocalDate, Integer> dailyTotalUsers = new HashMap<>();

        // 统计每日的新增用户数
        for (User user : allUsers) {
            LocalDate userDate = user.getCreateTime().toLocalDate();
            dailyNewUsers.put(userDate, dailyNewUsers.getOrDefault(userDate, 0) + 1);
        }

        // 累计总用户量
        int cumulativeTotalUsers = allUsers.size();
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            cumulativeTotalUsers += dailyNewUsers.getOrDefault(date, 0);
            dailyTotalUsers.put(date, cumulativeTotalUsers);
        }

        // 构造返回结果
        List<String> dateList = new ArrayList<>();
        List<String> newUserList = new ArrayList<>();
        List<String> totalUserList = new ArrayList<>();

        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
            newUserList.add(String.valueOf(dailyNewUsers.getOrDefault(date, 0)));
            totalUserList.add(String.valueOf(dailyTotalUsers.getOrDefault(date, 0)));
        }

        userReportVO.setDateList(String.join(",", dateList));
        userReportVO.setNewUserList(String.join(",", newUserList));
        userReportVO.setTotalUserList(String.join(",", totalUserList));

        return userReportVO;
    }

}
